package com.lock.reentrantLock;

import java.util.Random;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @PackageName:com.lock.reentrantLock
 * @ClassName:Test05
 * @Description:
 * @Author: zhangxiaoyu
 * @date 2021/1/19 17:13
 */
public class Test05 {

    static  class  IntLock implements Runnable{

        public static Lock lock1 = new ReentrantLock();

        public static Lock lock2 = new ReentrantLock();

        int lockNum;

        public IntLock(int lockNum) {
            this.lockNum = lockNum;
        }

        @Override
        public void run() {

            try {
                if(lockNum%2 == 1){ //奇数

                    lock1.lockInterruptibly();
                    System.out.println(Thread.currentThread().getName()+"获得锁1，还需要获得锁2");
                    Thread.sleep(new Random().nextInt(500));

                    lock2.lockInterruptibly();
                    System.out.println(Thread.currentThread().getName()+"同时获得了锁1和锁2");

                }else {   //偶数

                    lock2.lockInterruptibly();
                    System.out.println(Thread.currentThread().getName()+"获得锁2，还需要获得锁1");
                    Thread.sleep(new Random().nextInt(500));

                    lock1.lockInterruptibly();
                    System.out.println(Thread.currentThread().getName()+"同时获得了锁1和锁2-----");
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock1.unlock();
                lock2.unlock();
                System.out.println(Thread.currentThread().getName()+"线程退出");
            }

        }
    }

    public static void main(String[] args) throws InterruptedException {

        IntLock intLock = new IntLock(11);
        IntLock intLock1 = new IntLock(22);

        Thread t1 = new Thread(intLock);
        Thread t2 = new Thread(intLock1);

        t1.start();
        t2.start();

        //在主线程中，等待3000秒 如果还有线程没有结束就中断线程
        Thread.sleep(3000);

        if(t1.isAlive()){
            t1.interrupt();
        }

        if(t2.isAlive()){
            t2.interrupt();
        }
    }
}
